#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setFixedSize(this->width(),this->height());

    manager=new QNetworkAccessManager(this);

    //连接信号与槽
    connect(manager,&QNetworkAccessManager::finished,this,&Widget::ReplyFunc);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::closeEvent(QCloseEvent *event)      //关闭窗口时保存日志
{
    QString strText=ui->textEdit_history->toPlainText();

    QFile file("log.txt");
    if(file.open(QFileDevice::Append|QFileDevice::Text))
    {
        QTextStream out(&file);     //out是输出，从程序到文件，屏幕都属于输出，所以写对应out

        out<<strText<<"\n";

        file.close();
    }
    event->accept();
}

void Widget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    QLinearGradient gradient(0,0,width(),height());

    gradient.setColorAt(0,Qt::red);
    gradient.setColorAt(1,Qt::green);

    painter.fillRect(rect(),gradient);
}

void Widget::ReplyFunc(QNetworkReply* reply)
{
    QString strAll=reply->readAll();

    //解析json格式
    QJsonParseError jsonErrror;
    QJsonDocument json=QJsonDocument::fromJson(strAll.toUtf8(),&jsonErrror);

    if(jsonErrror.error==QJsonParseError::NoError) //json解析是否出错
    {
        if(json.isObject()) //是否为对象类型
        {
            QJsonObject rootobj=json.object();   //根对象

            if(rootobj.contains("trans_result"))
            {
                QJsonValue resultValue=rootobj.value(QString("trans_result"));
                QString strMean="";   //定义一个翻译结果汇总

                QJsonArray array=resultValue.toArray();

                for(auto it :array)
                {
                    QJsonObject obj=it.toObject();
                    if(obj.contains("dst"))
                    {
                         QJsonValue dst=obj.value(QString("dst"));
                         strMean+=dst.toString();     //将翻译结果拼接
                    }

                }
                ui->textEdit_result->append(strMean);    //翻译结果
            }
        }
    }


   //显示
    ui->textEdit_history->append(ui->textEdit_origin->toPlainText()+"  "+ui->textEdit_result->toPlainText());
    ui->textEdit_origin->clear();

}

void Widget::on_pushButton_translate_clicked()    //翻译
{


    QString originText=ui->textEdit_origin->toPlainText().trimmed();   //要翻译内容

    QString appid="20250316002305007";

    QString key="Bkdj4QOyrHBEtU4RzPFP";

    if(originText.isEmpty())
    {
        QMessageBox::information(this,"tip","请要输入的文本内容");
        return;
    }

    QString salt=QString::number(QRandomGenerator::global()->bounded(1000000,9999999999));

    qDebug() << "生成的 salt 值: " << salt;
    QString signStr=appid+originText+salt+key;
    qDebug() << "拼接后的签名字符串: " << signStr;
    // 计算MD5签名
    QByteArray md5Bytes = QCryptographicHash::hash(signStr.toUtf8(), QCryptographicHash::Md5);
    QString sign = md5Bytes.toHex();                     //计算签名
    qDebug() << "计算得到的签名: " << sign;
    //
    QString target="en";
    if (ui->comboBox->currentText() == "中文翻英文")
    {
        target = "en";
    } else if (ui->comboBox->currentText() == "英文翻中文")
    {
        target = "zh";
    }
    QString strAPI=QString("http://api.fanyi.baidu.com/api/trans/vip/translate")
            +"?q="+originText
            +"&from=auto"
            +"&to="+target
            +"&appid="+appid
            +"&salt="+salt
            +"&sign="+sign;

    //发送请求
    QNetworkRequest request;  //创建请求对象
    request.setUrl(strAPI);     //请求url

    manager->get(request);
    ui->textEdit_result->clear();


}

void Widget::on_pushButton_clear_clicked()
{
    ui->textEdit_history->clear();
}




//
